<script setup>
import {nextTick, onMounted, ref} from "vue";
import {addUser, deleteUser, getUserList, recoverUser, updateUser} from "@/api/user.js";
import {ElMessage, ElNotification} from "element-plus";

const userList = ref([])
const addUserDrawer = ref(false)
const updateUserDrawer = ref(false)
const userRole = JSON.parse(localStorage.getItem('token')).user.role
const newUser = ref({
  username: '',
  password: '',
  nickname: ''
})

const updateUserData = ref({
  id: '',
  nickname: '',
  slogan: ''
})

const getUserListAll = async () => {
  const list = await getUserList()
  if (list.code !== 200) {
    ElNotification({
      title: '接口错误',
      message: '获取用户列表失败！',
      type: 'error',
    })
  }
  userList.value = list.data
  if (userRole === '2') {
    userList.value = userList.value.filter(user => user.user.role === '2')
  }
  if (userRole === '1') {
    const filterList = userList.value
        .filter(item => item.user.role === '0')
        .map(item => {
          return {
            user: {
              ...item.user,
              nickname: "权限不足，无法查看",
              avatar: "权限不足，无法查看",
              slogan: "权限不足，无法查看"
            },
            info: item.info
          }
        })
    userList.value = userList.value
        .filter(item => item.user.role === '1' || item.user.role === '2')
    userList.value = userList.value.concat(filterList)
  }
}
const openAddUserDrawer = () => {
  addUserDrawer.value = true
}

const openUpdateUserDrawer = (user) => {
  updateUserDrawer.value = true
  updateUserData.value = {
    id: user.id,
    nickname: user.nickname,
    slogan: user.slogan
  }
}

const saveNewUser = async () => {
  if (newUser.value.username === '') {
    ElMessage.error('用户名不能为空！')
    return
  }
  if (newUser.value.password === '') {
    ElMessage.error('密码不能为空！')
    return
  }
  if (newUser.value.nickname === '') {
    ElMessage.error('昵称不能为空！')
    return
  }
  const result = await addUser({"user": newUser.value})
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '添加用户成功！',
      type: 'success',
    })
    newUser.value = {
      username: '',
      password: '',
      nickname: ''
    }
    addUserDrawer.value = false
    await nextTick()
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '添加用户失败！',
      type: 'error',
    })
  }
}

const deleteUserById = async (id) => {
  const result = await deleteUser(id)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '删除用户成功！',
      type: 'success',
    })
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '删除用户失败！',
      type: 'error',
    })
  }
}

const recoverUserById = async (id) => {
  const result = await recoverUser(id)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '恢复用户成功！',
      type: 'success',
    })
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '恢复用户失败！',
      type: 'error',
    })
  }
}

async function updateUserById() {
  const result = await updateUser(updateUserData.value)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '修改用户信息成功！',
      type: 'success',
    })
    updateUserDrawer.value = false
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '修改用户信息失败！',
      type: 'error',
    })
  }
}


onMounted(async () => {
  await getUserListAll()
})


</script>

<template>
  <div class="user-operation">
    <el-button type="primary" v-if="userRole !== '2'" size="default" @click="openAddUserDrawer">添加用户</el-button>
    <el-drawer v-model="addUserDrawer" title="添加用户" :with-header="true">
      <div class="add-user-item">
        <span class="input-label">用户名: </span>
        <el-input v-model="newUser.username" placeholder="请设置用户名"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">密码: </span>
        <el-input v-model="newUser.password" placeholder="请设置密码"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">昵称: </span>
        <el-input v-model="newUser.nickname" placeholder="请设置昵称"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="saveNewUser">添加用户</el-button>
      </div>
    </el-drawer>
    <el-drawer v-model="updateUserDrawer" title="修改用户" :with-header="true">
      <input v-model="updateUserData.id" type="text" hidden></input>
      <div class="add-user-item">
        <span class="input-label">昵称: </span>
        <el-input v-model="updateUserData.nickname" placeholder="请修改昵称"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">签名: </span>
        <el-input v-model="updateUserData.slogan" placeholder="请修改个性签名"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="updateUserById">修改信息</el-button>
      </div>
    </el-drawer>
  </div>
  <div class="user-list">
    <el-table
        :data="userList"
        border
        class="user-table"
    >
      <el-table-column prop="user.id" label="ID" align="center" width="100"/>
      <el-table-column prop="user.nickname" label="昵称" align="center" min-width="200" max-width="250"/>
      <el-table-column label="头像" align="center" width="100">
        <template #default="scope">
          <el-avatar :src="scope.row.user.avatar" shape="square" size="large"/>
        </template>
      </el-table-column>
      <el-table-column prop="user.slogan" label="个性签名" align="center" min-width="200"/>
      <el-table-column prop="user.createTime" label="注册时间" align="center" min-width="200" max-width="250"/>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.user.status"
              :active-value="'1'"
              :inactive-value="'0'"
              size="default"
              disabled
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" v-if="userRole !== '2'">
        <template #default="scope">
          <div class="operation-btns" v-if="scope.row.user.role !== '0' || userRole === '0'">
            <el-button type="primary" size="small">详情</el-button>
            <el-button type="success" size="small" @click="openUpdateUserDrawer(scope.row.user)">修改</el-button>
            <el-button v-if="scope.row.user.status === '1'" type="danger" size="small"
                       @click="deleteUserById(scope.row.user.id)">禁用
            </el-button>
            <el-button v-if="scope.row.user.status === '0'" type="warning" size="small"
                       @click="recoverUserById(scope.row.user.id)">恢复
            </el-button>
          </div>
          <div class="operation-btns" v-else>
            <el-text type="danger">权限不足，无法操作</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" v-if="userRole === '2'">
        <template #default="scope">
          <el-text type="danger">普通用户无权操作</el-text>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.user-operation {
  margin-bottom: 20px;
}

.user-table {
  position: relative;
}

.add-user-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  margin-right: 10px;
  width: 80px;
  text-align: right;
  font-weight: bold;
  color: #606266;
}

.add-user-btn {
  width: 100%;
  margin-top: 50px;
}

.operation-btns {
  display: flex;
  justify-content: center;
}

</style>
